<template>
    <div class="minor-table">
        <!-- edu-table不支持分页功能，暂时使用el-table处理 -->
        <el-table
            :data="tableData"
            :span-method="arraySpanMethod"
            style="width: 100%"
            :border="true"
            :cell-style='cellStyleMethod'
            @cell-click='cellCLickMethod'
            tooltip-effect="light"
        > 
            <el-table-column align="left" min-width="150" label="课程代码">
                <template slot-scope="props">
                    <div v-if="props.row.isCategoryRow" style="line-height: 50px">
                        <span class="minor-table-credit">{{props.row.sequence}} {{props.row.label}}</span>
                        <!-- <el-button v-if="operationFlag" type="primary" @click="addRow(props)">新增课程</el-button>
                        <el-button
                            v-if="operationFlag"
                            type="primary"
                            @click="mergeRow(props)"
                        >分组</el-button> -->
                        <!-- <span
                            class="minor-table-credit"
                        >{{ props.row.label }} {{ props.row.credit }}学分</span>
                        <span v-if="operationFlag && props.row.isWrongScore" class="minor-table-credit" style="color: red">所选课程学分总和未达到{{ props.row.label }}总学分要求，请继续添加课程</span> -->
                    </div>
                    <div v-else-if="!operationFlag">
                        <span>{{props.row.courseCode}}</span>
                    </div>
                    <div v-else-if="props.row.divide">
                        <span>{{props.row.courseCode}}</span>
                    </div>
                    <div v-else>
                        <el-checkbox
                            v-if="operationFlag && !props.row.courseGroupId && !props.row.parentId && (props.row.type == 2 && props.row.dataSource == 1 && advancedType == props.row.advancedType && type == 2 || type == 1)"
                            v-model="props.row.isCourseCheck"
                            :label="props.row.courseCode"
                            :key="props.row.courseCode"
                            @change="pickCourse(props.row.id, props.$index, 1)"
                        ></el-checkbox>
                        <span v-else>{{props.row.courseCode}}</span>
                    </div>
                </template>
            </el-table-column>
            <el-table-column
                align="center"
                prop="name"
                min-width="150"
                show-overflow-tooltip
                label="课程名称"
            >
                <template slot-scope="props">
                    <span
                        :class="{
                            'new-record-minor': props.row.changeStatus == 1,
                            'edit-record-minor': props.row.changeStatus == 2,
                            'remove-record-minor': props.row.changeStatus == 3
                        }"
                    >
                        {{ props.row.name }}
                    </span>
                </template>
            </el-table-column>
             <el-table-column
                align="center"
                min-width="150"
                show-overflow-tooltip
                label="模块"
            >
                <template slot-scope="props">
                    <div v-if="props.row.isCategoryRow" style="line-height: 50px;margin-left:40px;float:left;">
                        <template v-if="!props.row.hasChild">
                            <el-button v-if="operationFlag" type="primary" @click="addRow(props)">新增课程</el-button>
                            <el-button v-if="operationFlag && props.row.hasCourse" type="primary" @click="mergeRow(props, 1)">分模块</el-button>
                            <el-button
                                v-if="operationFlag && props.row.hasCourse"
                                type="primary"
                                @click="mergeRow(props, 2)"
                            >分组</el-button>
                        </template>
                    </div>
                    <div v-else>
                        <template v-if="props.row.courseGroupId">
                            <el-checkbox
                                class="course-checkbox"
                                v-if="(props.row.type == 2 && props.row.dataSource == 1 && advancedType == props.row.advancedType && type == 2 || type == 1) && operationFlag && !props.row.parentId"
                                v-model="props.row.isModuleCheck"
                                @change="pickCourse(props.row.id, props.$index, 2)"
                            ></el-checkbox>
                            <span>{{ props.row.modelName }}</span>
                            <i
                                class="el-icon-delete"
                                @click="deleteDivide(props.row.courseGroupId)"
                                v-if="(props.row.type == 2 && props.row.dataSource == 1 && advancedType == props.row.advancedType && type == 2 || type == 1) && operationFlag && !props.row.parentId"
                                style="color:red;cursor:pointer;position:absolute;right:4px;bottom:8px;padding:4px"
                                title="删除模块"
                            ></i>
                        </template>
                    </div>
                </template>
            </el-table-column>
            <el-table-column
                align="center"
                min-width="150"
                prop="courseGroupName"
                show-overflow-tooltip
                label="分组"
            >
                <template slot-scope="props" v-if="props.row.parentId">
                    <el-checkbox
                        class="course-checkbox"
                        v-if="(props.row.type == 2 && props.row.dataSource == 1 && advancedType == props.row.advancedType && type == 2 || type == 1) && operationFlag"
                        v-model="props.row.isGroupCheck"
                        @change="pickCourse(props.row.id, props.$index, 3)"
                    ></el-checkbox>
                    <span>{{ props.row.groupName}}</span>
                    <i
                        class="el-icon-delete"
                        @click="deleteDivide(props.row.parentId)"
                        v-if="(props.row.type == 2 && props.row.dataSource == 1 && advancedType == props.row.advancedType && type == 2 || type == 1) && operationFlag"
                        style="color:red;cursor:pointer;position:absolute;right:4px;bottom:8px;padding:4px"
                        title="删除课程分组"
                    ></i>
                </template>
            </el-table-column>
            <!-- <el-table-column align="center" min-width="250" show-overflow-tooltip label="先修课程要求">
                <template slot-scope="props">
                    <el-select
                        v-if="props.row.edit && preCourseList.length!=0"
                        v-model="props.row.preName"
                        style="margin-left: 20px;"
                        multiple
                        collapse-tags
                    >
                        <el-option
                            v-for="item in preCourseList"
                            :key="item.id"
                            :label="item.prerequisiteCourseName"
                            :value="item.id"
                        ></el-option>
                    </el-select>
                    <div v-else>
                        <span v-for="(item,index) in props.row.prerequisiteCourseList" :key="index">
                            <span>{{index>0?'、':''}}</span>
                            <span>{{item.prerequisiteCourseName}}</span>
                        </span>
                    </div>
                </template>
            </el-table-column>-->
            <el-table-column align="center" min-width="120" label="考试/考查">
                <template slot-scope="props">
                    <el-select size="mini" v-model="props.row.examMode" v-if="props.row.edit && !(props.row.dataSource == 2 && type == 2)">
                        <el-option label="考查" value="1" />
                        <el-option label="考试" value="0" />
                    </el-select>
                    <span v-else>{{props.row.examModeName}}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" prop="credits" label="学分">
                <template slot-scope="props">{{(props.row.credits*1).toFixed(2)}}</template>
            </el-table-column>
            <el-table-column align="center" prop="compulsory" label="是否必修">
                <template slot-scope="props">
                    <span v-if="props.row.compulsory == 1">是</span>
                    <span v-else-if="props.row.compulsory == 0">否</span>
                    <span v-else>{{props.row.compulsory}}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" min-width="120" prop="week" label="学时/周数"></el-table-column>
            <el-table-column align="center" label="各学期周学时分配/周数分配">
                <el-table-column align="center"  :label="schooolTermItem.label" v-for='(schooolTermItem, k) in semesterListMap' :key='k'>
                    <template slot-scope="props">
                        <div v-if='!props.row.edit && props.row.semester && props.row.semester.indexOf(k + 1) > -1'>
                           {{props.row.weekSchoolHour_}}
                        </div>
                    </template>
                </el-table-column>
            </el-table-column>
            <el-table-column align="center" show-overflow-tooltip min-width="200" label="备注">
                <template slot-scope="props">
                    <el-input
                        v-if="props.row.edit  && !(props.row.dataSource == 2 && type == 2)"
                        v-model="props.row.remarks"
                        class="minor-table-input-number"
                    ></el-input>
                    <div v-else>{{ props.row.remarks }}</div>
                </template>
            </el-table-column>
            <el-table-column
                v-if="operationFlag"
                align="center"
                fixed="right"
                width="220"
                label="操作"
            >
                <template slot-scope="props">
                    <template>
                        <!-- <el-button
                            v-if="props.row.addFlag && !(props.row.type=='2' && props.row.dataSource =='2')"
                            type="text"
                            @click="addPre(props)"
                        >添加先修课</el-button>-->
                        <template v-if="props.row.edit">
                            <el-button type="text" @click="saveCourse(props)">保存</el-button>
                            <el-button type="text" @click="cancelEdit(props.$index)">取消</el-button>
                        </template>
                        <template v-else>
                            <el-button type="text" @click="edit(props)" :disabled="type == 2 && (props.row.type ==2 && props.row.dataSource == 1 && advancedType != props.row.advancedType || (!!props.row.semester && !props.row.originSemesterConfig && props.row.dataSource == 2))">编辑</el-button>
                        </template>
                        <!-- dataSource 为2 是模板带到方案的课程 originSemesterConfig模板中未配置周学时为true-->
                        <el-button
                            type="text"
                            @click="remove(props)"
                            :disabled="type == 2 && (props.row.type ==2 && props.row.dataSource == 1 && advancedType != props.row.advancedType || props.row.dataSource == 2)"
                        >删除</el-button>
                    </template>
                </template>
            </el-table-column>
        </el-table>
        <add-course :params="params" v-if="addRowFlag" :show.sync="addRowFlag" :advancedType="advancedType" @init="getTemplete" ref="addCourse" />
        <add-pre-course
            :params="params"
            v-if="addPreCourseFlag"
            @init="getTemplete"
            ref="addPreCourse"
        />
        <divide-into-group
            v-if="addDivideFlag"
            :dialogInfo="params"
            :show.sync="addDivideFlag"
            @init="getTemplete"
            ref="addDivide"
        />
    </div>
</template>

<script>
import {
    minorMinorCourseLabelRelationList,
    minorCourseLabelRelation,
    deleteDivideGroup,
    deleteCourse
} from "common/src/api/minor/minorCulturePlanManager";
import AddCourse from "./AddCourse";
import AddPreCourse from "./AddPreCourse";
import DivideIntoGroup from "./DivideIntoGroup";
import lectureInformationdetailVue from '../../culture/lectureInformation/lectureInformationdetail.vue';
export default {
    name: "MinorTable",
    components: { AddCourse, AddPreCourse, DivideIntoGroup },
    props: {
        templateId: {
            default: null,
            type: Number
        },
        type: {
            default: 1,
            type: Number
        },
        operationFlag: {
            default: true,
            type: Boolean
        },
        schoolTerm: {
            default: 6,
            type: Number
        },
        advancedType: {
            default: '',
            type: String
        }
        // colspan: {
        //     default:
        //         (this.type == 1)
        //             ? (this.operationFlag
        //                 ? 17
        //                 : 16)
        //             : (this.operationFlag
        //             ? 18
        //             : 15),
        //     type: Number
        // }
    },
    data() {
        return {
            params: "",
            // 几选几分组主要是查看courseGroupId是否相同
            semesterList: [],
            tableData: [],
            addRowFlag: false,
            addPreCourseFlag: false,
            addDivideFlag: false,
            divideData: [],
            preCourseList: [],
            semesterListMap: [],
            curCheck: [],
            divideModuleFormLevel: '',
            advancedTypeMap: [10002, 10003, 10004]
        };
    },

    methods: {
        //合并单元计算
        delPreGroup() {
            this.$message({
                type: "warning",
                message: "请先删除分组后再进行该操作"
            });
        },
        arraySpanMethod({ row, columnIndex }) {
            if (row.isCategoryRow) {
                if (columnIndex === 0) {
                    return {
                        rowspan: 1,
                        colspan: 2
                    };
                } else if (columnIndex === 2) {
                    let fixedColumns = 7 + parseInt(this.schoolTerm || 0);
                    let colspan = fixedColumns;
                    if (this.operationFlag) {
                        colspan += 1; // (1代表操作列)
                    }
                    return {
                        rowspan: 1,
                        colspan: colspan
                    };
                }else {
                    return {
                        rowspan: 0,
                        colspan: 0
                    };
                }
            } else {
                if (columnIndex === 2) {
                    return {
                        rowspan: row.mergeModelSpan,
                        colspan: row.mergeModelSpan == 0 ? 0 : 1
                    };
                }
                if (columnIndex === 3) {
                    return {
                        rowspan: row.mergeGroupSpan,
                        colspan: row.mergeGroupSpan == 0 ? 0 : 1
                    };
                }
            }
        },
        edit({ row, $index }) {
            // if (row.rowspan !== 1) {
            //     this.delPreGroup();
            //     return;
            // }
            if (row.semester) {
                 (row.semesterListMap || []).forEach(item =>{
                    if (row.semester.indexOf(item.key) > -1) {
                        item.checked = true;
                    }
                });
            }
            // this.preCourseList = JSON.parse(
            //     JSON.stringify(row.prerequisiteCourseList)
            // );
            // 编辑后取消，下次再编辑时展示初始值。
            this.semesterInit();
            this.tableData = this.tableData.map((el, index) => {
                if (index === $index) {
                    el.edit = true;
                    // el.preName = el.prerequisiteCourseList.map(item => {
                    //     return item.id;
                    // });
                }
                return el;
            });
        },
        addPre({ row, $index }) {
            if (row.rowspan !== 1) {
                this.delPreGroup();
                return;
            }
            // 调用增加先修课方法
            this.addPreCourseFlag = true;
            this.params = {
                relationId: row.id,
                trainingId: row.trainingId,
                type: row.type
            };
            this.$nextTick(() => {
                this.$refs.addPreCourse.openDialog();
            });
        },
        remove({ row }) {
            // if (row.rowspan !== 1) {
            //     this.delPreGroup();
            //     return;
            // }
            if (row.courseGroupId != '' || row.parentId != '') {
                this.$message({
                    message: '已经分组或者分模块的课程不能删除',
                    type: 'warning'
                })
                return;
            }
            // 调用删除接口删除数据
            this.$eduConfirm("您确定要删除该数据吗", "删除").then(() => {
                let id = row.id;
                deleteCourse(id).then(({ code, data }) => {
                    if (code == 200) {
                        this.$message({
                            message: '操作成功',
                            type: 'success'
                        })
                        this.getTemplete();
                    }
                });
            });
        },
        addRow({ row, $index }) {
            this.addRowFlag = true;
            this.params = {
                labelId: row.labelId,
                trainingId: row.taringingId,
                type: parseFloat(row.type)
            };
            // this.$nextTick(() => {
            //     this.$refs.addCourse.openDialog();
            // });
        },
        canCheck(id, index, level) {
            if (!this.curCheck.length) return true;
            let validPass = false;
            let lastCheckObj = this.tableData.find(
                c => c.id == this.curCheck[this.curCheck.length - 1]
            )
            let curCheckObj = this.tableData[index];
            if (lastCheckObj.labelId == curCheckObj.labelId) {
                if (level == 1) {
                    if (lastCheckObj.level == '' || lastCheckObj.level == null) {
                        validPass = true;
                    }
                }else if (level == 2) {
                    if (lastCheckObj.level == 3) {
                        validPass = true;
                    }
                }else {
                    if (lastCheckObj.level == 2) {
                        validPass = true;
                    }
                }
            }
            if (!validPass) {
                this.cancelCheck(level, index);
                this.showMessage();
            }
            return validPass;
        },
        cancelCheck(level, index) {
            switch (level) {
                case 1:
                    this.tableData[index].isCourseCheck = false;
                    break
                case 2:
                    let curGroupId = this.tableData[index].courseGroupId;
                    this.tableData.forEach(c => {
                        if (c.courseGroupId == curGroupId) {
                            c.isModuleCheck = false;
                        }
                    })
                    break
                case 3:
                    let curPid = this.tableData[index].parentId;
                    this.tableData.forEach(c => {
                        if (c.parentId == curPid) {
                            c.isGroupCheck = false;
                        }
                    })
                    break
            }
        },
        showMessage() {
            this.$message({
                message: '不能跨类别、课程、模块、分组操作',
                type: 'warning'
            })
            return;
        },
        pickCourse(id, index, level) {
            if (event.target.checked) {
                if (this.canCheck(id, index, level)) {
                    this.divideModuleFormLevel = level;
                    switch (level) {
                        case 1:
                            this.curCheck.push(id);
                            break
                        case 2:
                            let curGroupId = this.tableData[index].courseGroupId;
                            this.tableData
                                .filter(c => c.courseGroupId == curGroupId)
                                .forEach(cg => this.curCheck.push(cg.id))
                            break
                        case 3:
                            let curPid = this.tableData[index].parentId
                            this.tableData
                                .filter(c => c.parentId == curPid)
                                .forEach(cg => this.curCheck.push(cg.id))
                            break
                    }
                }
            } else {
                if (this.curCheck.indexOf(id) >= 0) {
                    switch (level) {
                        case 1:
                            this.curCheck.splice(this.curCheck.indexOf(id), 1)
                            this.tableData[index].isCourseCheck = false;
                            break
                        case 2:
                            let curGroupId = this.tableData[index].courseGroupId
                            let gids = [];
                            this.tableData.forEach(c => {
                                if (c.courseGroupId == curGroupId) {
                                    gids.push(c.id)
                                }
                            })
                            var copyCurCheck = _.cloneDeep(this.curCheck)
                            this.curCheck = []
                            copyCurCheck.forEach(c => {
                                if (gids.findIndex(g => g == c) == -1) {
                                    this.curCheck.push(c)
                                }
                            })
                            break
                        case 3:
                            var curPid = this.tableData[index].parentId
                            var copyCurCheck = _.cloneDeep(this.curCheck)
                            var pids = []
                            this.tableData.forEach(c => {
                                if (c.parentId == curPid) {
                                    pids.push(c.id)
                                }
                            })
                            this.curCheck = []
                            copyCurCheck.forEach(c => {
                                if (pids.findIndex(p => p == c) == -1) {
                                    this.curCheck.push(c)
                                }
                            })
                            break
                    }
                }
            }
            if (this.curCheck.length == 0) {
                this.divideModuleFormLevel = ''
            }
        },
        mergeRow({row}, operate) {
            if (!this.curCheck.length) {
                this.$message({
                    message: operate == 1 ? '未选择可分模块的有效数据': '未选择可分组的有效数据',
                    type: 'warning'
                })
                return;
            }
            if (this.curCheck.length <= 1) {
                this.$message({
                    message: '分组或者分模块的课程数必须大于1门',
                    type: 'warning'
                })
                return;
            }
            let currentCourses = [], canChangeLimitType = true, limitType = '0', num = 0, num1 = 0;
            let curLabelIds = [];
            this.curCheck.forEach(id =>{
                let course = this.tableData.find(item =>{
                    return item.id == id;
                })
                if (course) {
                    if (course.mergeModelSpan > 1) {
                        num1 += 1;
                    }
                    curLabelIds.push(course.labelId);
                    currentCourses.push(course);
                }
            })
            num = this.curCheck.length;
            let isCurOperate = curLabelIds.every(ci => ci == row.labelId)
            if (!isCurOperate) {
                    this.$message({
                        message: '请选择当前类别下的课程进行操作',
                        type: 'warning'
                    })
                    return
            }
            if (this.divideModuleFormLevel == 2 && operate == 2) {
                num = num1;
            }
            if (this.divideModuleFormLevel == 2 && operate == 1) {
                this.$message({
                    message: '模块不能再次划分模块',
                    type: 'warning'
                })
                return
            }
            if (this.divideModuleFormLevel == 3 && operate == 2) {
                this.$message({
                    message: '分组不能再次划分分组',
                    type: 'warning'
                })
                return
            }
            if (this.divideModuleFormLevel == 3 && type == 1) {
                this.$message({
                    message: '分组不能再次划分模块',
                    type: 'warning'
                })
                return
            }
            if (row.limitType) {
                canChangeLimitType = false;
                limitType = this.currentRow.limitType;
            }
            this.addDivideFlag = true;
            this.params = {
                title: operate == 1 && '划分模块' || '课程分组',
                operate, //操作类型 1:分模块，2：分组
                level: this.divideModuleFormLevel, //当前勾选的复选框所属类型 1：课程前复选框；2：模块的复选框；3：分组的复选框
                currentCourses,
                courseIdList: this.curCheck,
                num,//模块框包含课程、模块
                canChangeLimitType,
                limitType
            }
        },
        cancelEdit(index) {
            this.tableData = this.tableData.map((el, row) => {
                if (row === index) {
                    el.edit = false;
                }
                return el;
            });
        },
        saveCourse(prop) {
            //整理接口数据，提交请求，成功后关闭编辑功能
            // let selectList = row.preName;
            // row.prerequisiteCourseList = row.prerequisiteCourseList.filter(
            //     item => {
            //         return selectList.indexOf(item.relationId) > -1;
            //     }
            // );
            let row = _.cloneDeep(prop.row);
            // if (row.examMode == 1) {
            //     row.examModeName = "考查";
            // } else if (row.examMode == 0) {
            //     row.examModeName = "考试";
            // }
            // for (let key in this.semesterList[$index]) {
            //     row[key] = this.semesterList[$index][key];
            // }
            let changedSemester = [];
            row.semesterListMap.forEach(spec => {
                if (spec.checked) {
                    changedSemester.push(spec.key);
                }
            })
            row.semester = changedSemester.join(',');
            row.projId = 1;
            //校验备注信息长度
            if(!!row.remarks && row.remarks.length>255){
                 this.$message({
                            type: "warning",
                            message: "备注内容过长"
                        });
                return;
            }else{
                //row.edit = false;
                row.changeStatus = '2';
                row.semesterListMap = '';
                minorCourseLabelRelation(row).then(({ code, data }) => {
                    if (code == 200) {
                        this.$message({
                            message: '操作成功',
                            type: 'success'
                        })
                        //row.semester = changedSemester;
                        this.getTemplete();
                        //this.$set(this.tableData, $index, row);
                    }
            });
            }
        },
        increase(prop) {
            this.semesterUpdata(prop, "increase");
        },
        decrease(prop) {
            this.semesterUpdata(prop, "decrease");
        },
        semesterInput(prop, value) {
            this.semesterUpdata(prop, value);
        },
        semesterUpdata(prop, value) {
            let index = prop.$index;
            let target = prop.column.property;
            if (value.endsWith(".")) {
                if (value.split(".").length > 2) {
                    this.$nextTick(() => {
                        this.semesterList[index][target] = 0;
                    });
                    return;
                } else {
                    return;
                }
            }
            let score = parseFloat(this.tableData[index].credits);
            let oldValue;
            let newValue;
            if (value === "increase") {
                oldValue = this.semesterList[index][target];
                newValue = oldValue + 1;
            } else if (value === "decrease") {
                oldValue = this.semesterList[index][target];
                if (oldValue > 0) {
                    this.$nextTick(() => {
                        this.semesterList[index][target] = oldValue - 1;
                    });
                    return;
                } else {
                    return;
                }
            } else {
                oldValue = this.tableData[index][target];
                newValue = parseFloat(value);
                if (!Number.isFinite(newValue) || newValue < 0) {
                    // 不提示，数据不变
                    if (value == "") {
                        this.$message({
                            type: "warning",
                            message: "学分不能为空"
                        });
                    } else if (newValue < 0) {
                        this.$message({
                            type: "warning",
                            message: "学分不能小于0"
                        });
                    } else {
                        this.$message({
                            type: "warning",
                            message: "数据输入有误，请重新输入"
                        });
                    }
                    this.$nextTick(() => {
                        this.semesterList[index][target] = oldValue;
                    });
                    return;
                }
            }
            let keys = Object.keys(this.semesterList[index]);
            let values = Object.values(this.semesterList[index]);
            keys.map((el, index) => {
                if (el.startsWith("semester") && el !== target) {
                    score -= parseFloat(
                        values[index] === "" ? 0 : values[index]
                    );
                }
            });
            if (score - newValue >= 0) {
                // 不提示，数据不变
                this.$nextTick(() => {
                    this.semesterList[index][target] = newValue;
                });
            } else {
                if (value == "increase") {
                    this.$nextTick(() => {
                        this.semesterList[index][target] = oldValue;
                    });
                } else {
                    // 错误提示，数据更新为初始值
                    this.$message({
                        type: "warning",
                        message: "各学期学分总合大于总学分，请重新输入"
                    });
                    this.$nextTick(() => {
                        this.semesterList[index][target] = 0;
                    });
                }
            }
        },
        semesterInit() {
            this.semesterList = this.tableData.map(el => {
                let json = {};
                for (let key in el) {
                    if (key.startsWith("semester")) {
                        json[key] = el[key];
                    }
                }
                return json;
            });
        },
        getTemplete() {
            let params = {
                trainingId: this.templateId,
                type: this.type //表示 1 模板 2 方案
            };
            if (this.advancedType && this.type == 2) {
                params.advancedType = this.advancedType;
            }
            minorMinorCourseLabelRelationList(params).then(({ code, data }) => {
                if (code == 200) {
                    this.dealTemplateData(data);
                    this.semesterInit();
                }
            });
        },
        dealTemplateData({
            courseLabelRelationList,
            minorCoursesLabelList
        }) {
            let headData = [], categoryParData = [], categoryChildData = [];
            minorCoursesLabelList.forEach(el => {
                el.isCategoryRow = true;
                if (!Number(el.parentId)){
                    categoryParData.push(el);
                }else {
                    categoryChildData.push(el);
                }
            });
            categoryParData.forEach((p, index) =>{
                p.children = categoryChildData.filter(child => {
                   return child.parentId == p.labelId
                });
                if (p.children.length) {
                    p.hasChild = true;
                    p.sequence = `${this.$utils.numberToChinese(index + 1)}、`
                }
                headData = [...headData, p, ...p.children];
            })
            let contentData = [];
            let tableData = [];
            headData.forEach((el, index) => {
                if (el.hasChild) {
                    contentData = [];
                }else {
                    contentData = courseLabelRelationList
                        .filter(item => {
                            return el.labelId == item.labelId;
                        })
                        .map(item => {
                            // for (let key in item) {
                            //     if (
                            //         key.startsWith("semester") &&
                            //         item[key] === ""
                            //     ) {
                            //         item[key] = 0;
                            //     }
                            // }
                            // let prerequisiteCourseList = (minorRelationCoursesRelationList || []).filter(
                            //     relation => {
                            //         return item.id == relation.relationId;
                            //     }
                            // );
                            // item.preName = prerequisiteCourseList.map(item => {
                            //     return item.id;
                            // });
                            //item.addFlag = index == 0 ? true : false;
                            el.hasCourse = true;
                            item.isModuleCheck = false; 
                            item.isGroupCheck = false; 
                            item.isCourseCheck = false; 
                            item.level = !item.level ? '' : item.level;
                            item.parentId = item.level == 2 ? item.courseGroupId : item.parentId;
                            item.courseGroupId = item.level == 2 ? '' : item.courseGroupId;
                            item.parentId = !item.parentId ? '' : item.parentId;
                            item.courseGroupId = !item.courseGroupId  ? '' : item.courseGroupId;
                            item.period = (item.period == null || item.period == undefined) ? '' : item.period;
                            item.weeks = (item.weeks == null || item.weeks == undefined) ? '' : item.weeks;
                            item.week = `${item.period}/${item.weeks}`;
                            if (item.examMode == 1) {
                                item.examModeName = "考查";
                            } else if (item.examMode == 0) {
                                item.examModeName = "考试";
                            }
                            item.isCategoryRow = false;
                            item.mergeGroupSpan = 1;
                            item.mergeModelSpan = 1;
                            //item.prerequisiteCourseList = prerequisiteCourseList || [];
                            item.semesterListMap = _.cloneDeep(this.semesterListMap);
                            return item;
                        });
                }
                // 解析分组分模块
                let newData = this.resolveDivideData(contentData);

                tableData = [...tableData, headData[index], ...newData];
            });
            this.curCheck = [];
            this.tableData = [...tableData];
            this.checkTotalScore(this.tableData);
        },
        checkTotalScore(tableData) {
            let isNext = true, tip = null;
            let categoryList = [];
            tableData.forEach((item) => {
                if(item.isCategoryRow && !item.hasChild){
                    categoryList.push({
                        label: item.label,
                        labelId: item.labelId,
                        credit: item.credit,
                        credit2: item.credit2,
                        credit3: item.credit3
                    })
                }
            })
            for (let i =0, len = categoryList.length; i < len; i++){
                let courseTotalScore = 0, el = categoryList[i], needScore= 0;
                tableData.forEach(item => {
                    if (item.labelId == el.labelId && !item.isCategoryRow) {
                        courseTotalScore += (item.credits * 1);
                    }
                })
                if (this.type == 1 || this.advancedTypeMap[0] == this.advancedType) {
                    needScore = el.credit * 1;
                }else if (this.advancedTypeMap[1] == this.advancedType) {
                    needScore = el.credit * 1 + el.credit2 * 1;
                }
                else {
                    needScore = el.credit * 1 + el.credit2 * 1 + el.credit3 * 1;
                }
                if (courseTotalScore < needScore) {
                    isNext = false;
                    tip = `所选课程学分总和未达到${el.label}总学分要求，请继续添加课程`;
                    break;
                }
            }
            this.tableData = [...tableData];
            this.$emit('selectChange', isNext, tip);
        },
        resolveDivideData(contentData) {
            if (!contentData.length) {
                return [];
            }
            contentData = contentData.sort((s1, s2) => {
                return Number(s1.courseCode) - Number(s2.courseCode);
            })
            let newContent = [];
            let  groupByparentIdData = _.groupBy(contentData, 'parentId');
            _.each(groupByparentIdData, (p, pIndex) => {
                let flag = true;
                let groupBycourseGroupIdData = _.groupBy(p, 'courseGroupId');
                _.each(groupBycourseGroupIdData, (g, gIndex) =>{
                    g.forEach((s, sIndex) => {
                        if (!gIndex) { // 未分模块
                            if (!sIndex) {
                                s.mergeGroupSpan = pIndex && p.length || 1;
                            }else {
                                s.mergeGroupSpan = !pIndex && 1 || 0; // 隐藏该列
                            }
                        }else {
                            if (!sIndex) {
                                if (flag) {
                                    s.mergeGroupSpan =  pIndex && p.length || 1;
                                }else {
                                    s.mergeGroupSpan =  !pIndex && 1 || 0;
                                }
                                s.mergeModelSpan = g.length;
                                flag = false;
                            }else {
                                s.mergeGroupSpan =  !pIndex && 1 || 0; // 隐藏该列
                                s.mergeModelSpan = 0; // 隐藏该列
                            }
                        }
                        newContent.push(s);
                    })
                })
            })
            return newContent;
            // let newData = contentData.sort((a, b) => {
            //     return a.courseGroupId - b.courseGroupId;
            // });
            // let arr = Array.from(
            //     new Set(
            //         contentData.map(el => {
            //             return el.courseGroupId;
            //         })
            //     )
            // );
            // let newArr = [];
            // arr.map(el => {
            //     let sameCourseGroup = newData.filter(item => {
            //         return item.courseGroupId === el;
            //     });
            //     sameCourseGroup = sameCourseGroup.map((row, index) => {
            //         if (row.courseGroupId == "") {
            //             row.divide = false;
            //             row.rowspan = 1;
            //         } else if (sameCourseGroup.length > 1) {
            //             if (index === 0) {
            //                 row.rowspan = sameCourseGroup.length;
            //             } else {
            //                 row.rowspan = 0;
            //             }
            //             row.divide = true;
            //         }
            //         return row;
            //     });
            //     newArr = [...newArr, ...sameCourseGroup];
            // });
            // return newArr;
        },
        deleteDivide(id) {
            let params = {
                id
            };
            this.$confirm('此操作将删除分组或模块, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteDivideGroup(params).then(({ code, data }) => {
                    if (code == 200) {
                        this.$message({
                            type: 'success',
                            message: '删除成功'
                        });
                        this.getTemplete();
                    }
                }).catch(() =>{
                    this.$message({
                        type: 'error',
                        message: '删除失败'
                    });
                })
            })
            
        },
        initSemesterListMap() {
            let list = [];
            let labelArr = ['一',  '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二', '十三', '十四', '十五', '十六', '十七', '十八', '十九', '二十'];
            for(let i = 0 ; i< this.schoolTerm; i++) {
                list.push({
                    label: labelArr[i],
                    checked: false,
                    key: i + 1
                })
            }
            this.semesterListMap = list;
        },
        cellStyleMethod({row, column, rowIndex, columnIndex}){
            if (column.label && row.semesterListMap) {
                let currentItem = _.find(row.semesterListMap, item => {
                    return item.label === column.label;
                })
                if (currentItem) {
                   if (row.edit) {
                        if (currentItem.checked) {
                            return 'background: #3A7FE8; cursor: pointer';
                        }
                        return "cursor: pointer";
                   }
                }
           }
        },
        cellCLickMethod(row, column) {
            if (!row.edit) return;
            if (column.label && row.semesterListMap) {
                let currentItem = _.find(row.semesterListMap, item => {
                    return item.label === column.label;
                })
                if (currentItem) {
                    currentItem.checked =  !currentItem.checked;
                }
           }
        }
    },
    mounted() {
        this.initSemesterListMap();
        this.getTemplete();  
    }
};
</script>

<style lang="scss" scoped>
.minor-table {
    font-size: 14px;
    .minor-table-credit {
        font-family: PingFangSC-Medium;
        color: #2b3b4e;
        letter-spacing: 0;
        line-height: 16px;
        margin-right: 48px;
    }
    .show-row-1 {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
    .course-checkbox {
        margin-right: 0px;
    }
}
.new-record-minor {
  color: #58c22a;
}

.edit-record-minor {
  color: #f56c6c;
}

.remove-record-minor {
  color: #aaa;
}
</style>
